package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Utilisateur;
import dao.DaoUtilisateur;

/**
 * Servlet implementation class Connexion
 */
public class Connexion extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Connexion() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		if((String)request.getParameter("disconnected") != null){
			System.out.println("disconnected");
			HttpSession session = request.getSession();
			session.setAttribute("user_connected", null);
			request.getRequestDispatcher( "/index.jsp").forward( request, response );
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		DaoUtilisateur daouser = new DaoUtilisateur();
		HttpSession session = request.getSession();
		
		Utilisateur user = null;
		
		if(daouser.checkExist(request.getParameter("login"), request.getParameter("pwd")) != null){
			user = daouser.checkExist(request.getParameter("login"), request.getParameter("pwd"));
			session.setAttribute("user_connected", user );
			request.getRequestDispatcher( "/accueil.jsp").forward( request, response );
		}
		else{
			request.setAttribute("connect_error", "1");
			request.getRequestDispatcher( "/index.jsp").forward( request, response );
		}
	}

}
